<?php
/**
 * Description: 获取用户订单列表
 * User: devforma
 * Date: 16/2/25
 * Time: 10:32
 */

class GetUserOrders implements iController {

    const EXPRESS_FEE = 30;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1)
            return genOutput(1000);

        $data = array();

        //获取该用户所有退款记录
        $refunds = $cmsdb->getResults("SELECT * FROM `refund_orders` WHERE `user_id`=:uid", array(':uid' => $queryArgs['user_id']));

        $rList = array();
        if (!empty($refunds)) {
            foreach ($refunds as $r) {
                $rList[$r->order_id] = $r;
            }
        }

        //获取所有购买记录
        $sql = 'SELECT p.id, p.order_id, o.create_time, c.cover_pic, c.course_name, o.price, o.platform, c.material_fee, c.refund_deadline, c.need_address
        FROM `relation_user_product` AS p, `original_orders` AS o, `data_live_course` AS c
        WHERE p.order_id=o.order_id AND p.product_id=c.id AND p.user_id=:uid AND p.product_type="zhiboke" AND o.price>0 ORDER BY p.id DESC';

        $purchasedCourses = $cmsdb->getResults($sql, array(':uid' => $queryArgs['user_id']));

        if (!empty($purchasedCourses)) {
            foreach ($purchasedCourses as $o) {

                if ($o->need_address) { //如果订单需要邮寄材料,检测物流状态
                    $expressStatus = $this->getExpressStatus($o->id);
                } else {
                    $expressStatus = 0;
                }

                $deadline = !empty($o->refund_deadline) ? strtotime($o->refund_deadline) : 0;
                if (!isset($rList[$o->order_id]) && time() < $deadline) { //没有退款记录且在退款期限内
                    $status = 'can_refund'; //可退款
                } elseif (isset($rList[$o->order_id]) && in_array($rList[$o->order_id]->status, [2, 3])) {
                    $status = 'refund_process'; //退款处理中
                } elseif (isset($rList[$o->order_id]) && $rList[$o->order_id]->status == 1) { //退款成功
                    continue;
                } elseif (isset($rList[$o->order_id]) && $rList[$o->order_id]->status == 0) {
                    $status = 'refund_fail'; //退款失败
                } else {
                    $status = 'no_refund'; //不可退款
                }

                $data[] = array(
                    'order_id' => intval($o->order_id),
                    'order_time' => explode(' ', $o->create_time)[0],
                    'course_name' => $o->course_name,
                    'price' => floatval($o->price),
                    'pay_platform' => $o->platform,
                    'has_express' => (bool)$o->need_address,
                    'status' => $status,
                    'cover_pic' => getSecureUrl($o->cover_pic),
                    'express_status' => $expressStatus,
                    'material_fee' => intval($o->material_fee),
                    'express_fee' => self::EXPRESS_FEE
                );
            }

            //退款退课成功的订单
            foreach ($rList as $r) {
                if ($r->status == 1) {
                    $info = $this->getOrderInfo($r->order_id);
                    $data[] = array(
                        'order_id' => intval($r->order_id),
                        'order_time' => explode(' ', $info->create_time)[0],
                        'course_name' => $info->course_name,
                        'price' => floatval($info->price),
                        'pay_platform' => $info->platform,
                        'has_express' => (bool)$info->need_address,
                        'status' => 'refund_success',
                        'cover_pic' => getSecureUrl($info->cover_pic),
                        'express_status' => 0,
                        'material_fee' => intval($info->material_fee),
                        'express_fee' => self::EXPRESS_FEE
                    );
                }
            }
        }

        return genOutput(1, array('list' => $data));
    }

    private function getOrderInfo($orderId) {
        global $cmsdb;

        //获取所有购买记录
        $sql = 'SELECT o.order_id, o.create_time, c.cover_pic, c.course_name, o.price, o.platform, c.material_fee, c.refund_deadline, c.need_address
        FROM `original_orders` AS o, `data_live_course` AS c
        WHERE o.product_id=c.id AND o.order_id=:oid';

        return $cmsdb->getRow($sql, array(':oid' => $orderId));
    }

    /**
     * 获取物流信息
     *
     * @param $rupId
     * @return int 0为未处理或退款中, 1为处理中
     */
    private function getExpressStatus($rupId) {
        global $cmsdb;

        $express = $cmsdb->getRow('SELECT `id`, `status` FROM `express_tasks` WHERE `rup_id`=:rupid AND `available` = 1', array(':rupid' => $rupId));
        if (!empty($express) && ($express->status == 1 || $express->status == 2)) { //如果有物流信息且已处理或已寄送,则需要在退款申请时处理退款金额
            return 1;
        }

        return 0;
    }
}